package org.webmev.controllers;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class DataAnalysisDispatcher extends HttpServlet {

    private static final long serialVersionUID = 1L;
    private static final String DATA_FILES_DIR_PATH = "/files";
    private File rootDataFilesDir;
    private HttpSession session;

    public DataAnalysisDispatcher() {
        super();
    }

    public void init(ServletConfig config) throws ServletException {

        super.init(config);

        String realPath = getServletContext().getRealPath(DATA_FILES_DIR_PATH);
        rootDataFilesDir = new File(realPath);
        if (!rootDataFilesDir.isDirectory()) {
            throw new ServletException(DATA_FILES_DIR_PATH + " is not a directory");
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        session = request.getSession(true);
        Map<String, String[]> params = request.getParameterMap();

        startProcess(params);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    }

    private void startProcess(Map<String, String[]> p) {

        if (session.getAttribute("startMeV").equals(null)) {
        }

//        FileManager fm = session.getAttribute("fileManagerIdentifier");
//        ProcessManager pm = session.getAttribute("processManagerIdentifier");
//        
//        if(fm == null){
//            fm = new FileManager();
//            session.setAttribute("fileManagerIdentifier", fm);
//        }
//        
//        if(pm == null){
//            pm = new ProcessManager();
//            session.setAttribute("processManagerIdentifier", pm);
//        }

        for (Entry<String, String[]> e : p.entrySet()) {
            String k = e.getKey();
            String[] vs = e.getValue();
            String fileName = "";
            String action = "";
            if (k.equals("file") && vs.length == 1) {
                fileName = vs[0];
//                for (String v : vs) {}
            } else if (k.equals("action") && vs.length == 1) {
                action = vs[0];
            }
//            if(!fileName.equals("") && fm.isExist(fileName))
            Object data = getDataFromFile(fileName);
//            if(!fileName.equals("") && fm.isExist(fileName)){
            if (action.equals("") || action.equals("heatmap")) {
                processHeatMap();
            }
//                }
//            }
        }
    }

    private void processHeatMap() {
    }

    private Object getDataFromFile(String fileName) {
        
        return null;
    }
}
